package com.yunxi.service.dubboService.impl.otd;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.bizToHub.pojo.EaiLogs;
import com.yunxi.bizToHub.service.EaiLogBizToHubService;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.otd.OtdOrderSo;
import com.yunxi.model.otd.OtdPlanChangeApply;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.otd.pojo.OtdPlanChangeApplyAddVO;
import com.yunxi.otd.pojo.OtdPlanChangeApplyEditVO;
import com.yunxi.otd.pojo.OtdPlanChangeApplyQueryVO;
import com.yunxi.otd.pojo.OtdPlanChangeApplyVO;
import com.yunxi.otd.pojo.VehicleCanChangePlanQueryVO;
import com.yunxi.otd.pojo.VehicleCanChangePlanVO;
import com.yunxi.otd.service.OtdChangeApplyDubboService;
import com.yunxi.otd.service.OtdOrderSoDubboService;
import com.yunxi.rocketMq.producer.OtdWeekPlanProducer;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.VehicleProductViewService;
import com.yunxi.service.localService.otd.OtdChangeApplyPlanService;
import com.yunxi.service.localService.otd.OtdIfProducePlanService;
import com.yunxi.service.localService.otd.OtdOrderSoService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.vehicle.pojo.VehicleProductViewVO;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;


/**
 * <p>
 * 生产计划变更申请 服务实现类
 * </p>
 *
 * @author XUQI
 * @since 2019-05-06
 */
//@Service(version = "${demo.service.version}",
//    application = "${dubbo.application.id}",
//    protocol = "${dubbo.protocol.id}",
//    registry = "${dubbo.registry.id}"
//)
public class OtdChangeApplyDubboServiceImpl implements OtdChangeApplyDubboService {

    private static final Log logger = LogFactory.getLog(OtdChangeApplyDubboServiceImpl.class);

    @Autowired
    @Qualifier("otdIfProducePlanServiceImpl")
    OtdIfProducePlanService planService;

    @Autowired
    @Qualifier("otdChangeApplyPlanServiceImpl")
    OtdChangeApplyPlanService applyPlanService;

    @Autowired
    @Qualifier("vehicleProductViewServiceImpl")
    VehicleProductViewService productService;

    @Autowired
    @Qualifier("vehicleOfflineServiceImpl")
    VehicleOfflineService carService;


    @Autowired
    @Qualifier("otdOrderSoServiceImpl")
    OtdOrderSoService soService;

    @Autowired
    OtdOrderSoDubboService otdOrderSoDubboService;


    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateService code;

    @Value("${mq.switch}")
    private String mq_switch;
  /*  @Autowired
    private OtdPlanProducer planProducer;*/

    @Autowired
    private OtdWeekPlanProducer otdWeekPlanProducer;

    @Autowired
    private EaiLogBizToHubService eaiLogBizToHubServiceImpl;

    @Override
    public PageInfo pageByVo(OtdPlanChangeApplyQueryVO queryVO, Integer pageNum, Integer pageSize) {
        return applyPlanService.pageByVo(queryVO, pageNum, pageSize);
    }

    /**
     * 查询可变更生产计划列表
     *
     * @param queryVO 查询条件
     * @param pageNum 页数
     * @param pageSize 行数
     * @return 分页对象
     */
    @Override
    public PageInfo findChangePlan(VehicleCanChangePlanQueryVO queryVO, Integer pageNum, Integer pageSize) {
        return carService.selectCanChangePlan(queryVO, pageNum, pageSize);
    }

    @Override
    public OtdPlanChangeApplyVO load(String applyId) {
        return applyPlanService.load(applyId);
    }

    /**
     * 新建申请单
     *
     * @param addVO VO
     * @return ApiResult
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult addApply(OtdPlanChangeApplyAddVO addVO) {
        List<String> planNoList = addVO.getPlanNoList();
        for (String planNo : planNoList) {

            //// 查询当前车辆信息
            VehicleOffline car = carService.selectCarByPlanNo(planNo);

            //创建申请单
            OtdPlanChangeApply changeApply = new OtdPlanChangeApply();
            BeanUtils.copyProperties(addVO, changeApply);
            changeApply.setPlanNo(planNo);
            changeApply.setOldProductCode(car.getProductCode());
            changeApply.setOldCustomPackCode(car.getCustomPackCode());
            changeApply.setPlanChangeApplyCode(code.createCode("PCHG", "yyMMdd", 4));
            changeApply.setState("1");

            // 申请类型：修改
            if ("U".equals(changeApply.getChangeType())) {
                //查询产品CODE
                String productCode = productService
                    .findProductCodeBySub(addVO.getVehicleCode(), addVO.getInColorCode(), addVO.getOutColorCode());

                if (StringUtils.isEmpty(productCode)) {
                    return ResponseUtil.fail(-1, "产品信息填写错误！");
                }
                changeApply.setNewProductCode(productCode);
                changeApply.setNewCustomPackCode(addVO.getCustomPackCode());
            } else {
                changeApply.setNewProductCode(car.getProductCode());
                changeApply.setNewCustomPackCode(car.getCustomPackCode());
            }
            applyPlanService.save(changeApply);
        }
        return ResponseUtil.ok();
    }


    @Override
    public ApiResult removeByIds(List<String> ids) {
        return applyPlanService.removeByIds(ids);
    }

    /**
     * 编辑申请单
     */
    @Override
    public ApiResult modifyApply(OtdPlanChangeApplyEditVO editVO) {
        //查询产品CODE
        String productCode = productService
            .findProductCodeBySub(editVO.getVehicleCode(), editVO.getInColorCode(), editVO.getOutColorCode());
        if (StringUtils.isEmpty(productCode)) {
            return ResponseUtil.fail(-1, "产品信息填写错误！");
        }

        OtdPlanChangeApply changeApply = new OtdPlanChangeApply();
        BeanUtils.copyProperties(editVO, changeApply);
        changeApply.setNewProductCode(productCode);
        changeApply.setNewCustomPackCode(editVO.getCustomPackCode());
        boolean result = applyPlanService.updateById(changeApply);
        if (!result) {
            return ResponseUtil.fail(-1, "编辑失败，请刷新后重试！");
        }
        return ResponseUtil.ok();
    }

    /**
     * 提交申请单
     */
    @Override
    public ApiResult releaseApply(String applyId, LoginInfo info) {
        OtdPlanChangeApply changeApply = applyPlanService.getById(applyId);
        if (!changeApply.getState().equals("1") && !changeApply.getState().equals("3")) {
            return ResponseUtil.fail(-1, "请查询后重试！");
        }
        changeApply.setUpdateBy(info.getUserCode());
        changeApply.setState("2");
        boolean result = applyPlanService.updateById(changeApply);
        if (!result) {
            return ResponseUtil.fail(-1, "请查询后重试！");
        }
        return ResponseUtil.ok();
    }

    /**
     * 生产申请审核
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult auditApply(String applyId, LoginInfo info) {
        OtdPlanChangeApply changeApply = applyPlanService.getById(applyId);
        if (!changeApply.getState().equals("2")) {
            return ResponseUtil.fail(-1, "请查询后重试！");
        }
        changeApply.setUpdateBy(info.getUserCode());
        changeApply.setState("4");
        boolean result = applyPlanService.updateById(changeApply);
        if (!result) {
            return ResponseUtil.fail(-1, "请查询后重试！");
        }

        //查询下发生产计划
        LambdaQueryWrapper<OtdOrderSo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OtdOrderSo::getPlanNo, changeApply.getPlanNo());
        OtdOrderSo orderSo = soService.getOne(wrapper);
        if (orderSo == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil.fail(-1, "未找到生产计划！");
        }
        orderSo.setInterfaceType(changeApply.getChangeType());
        VehicleProductViewVO product = null;// 产品信息
        if ("U".equals(changeApply.getChangeType())) {
            // 申请类型：修改
            orderSo.setProductCode(changeApply.getNewProductCode());
            orderSo.setCustomPackCode(changeApply.getNewCustomPackCode());
            orderSo.setCarName(soService.generateCarName(orderSo.getProductCode(), orderSo.getCustomPackCode()));
            product = productService.selectProductByCode(changeApply.getNewProductCode());
        } else {
            product = productService.selectProductByCode(changeApply.getOldProductCode());
        }
        orderSo.setSeriesCode(product.getSeriesCode());
        orderSo.setCatalogCode(product.getCatalogCode());
        orderSo.setColorCodeIn(product.getColorCodeIn());
        orderSo.setColorCodeOut(product.getColorCodeOut());
        orderSo.setModelCode(product.getModelCode());

        //转换JSON
        List<OtdOrderSo> orderList = new ArrayList<>();
        orderList.add(orderSo);
        String json = soService.generateSapJson(orderList);

        // 发送MQ消息
        if (mq_switch.equals("true")) {
            otdWeekPlanProducer.sendMessage(json);
        } else {
            EaiLogs eaiLogs = new EaiLogs();
            eaiLogs.setPmsEaiContent(json);
            eaiLogBizToHubServiceImpl.saveWeekPlanEaiLog(eaiLogs);
        }

        return ResponseUtil.ok();
    }

    /**
     * 驳回申请
     */
    @Override
    public ApiResult rejectApply(OtdPlanChangeApplyVO changeApplyVO, LoginInfo info) {
        OtdPlanChangeApply changeApply = applyPlanService.getById(changeApplyVO.getPlanChangeApplyId());
        if (!changeApply.getState().equals("2")) {
            return ResponseUtil.fail(-1, "请刷新后重试！");
        }
        changeApply.setRejectReason(changeApplyVO.getRejectReason());//驳回原因
        changeApply.setUpdateBy(info.getUserCode());
        changeApply.setState("3");//驳回
        boolean result = applyPlanService.updateById(changeApply);
        if (!result) {
            return ResponseUtil.fail(-1, "请刷新后重试！");
        }
        return ResponseUtil.ok();
    }

    @Override
    public VehicleCanChangePlanVO findPlanByPlanNo(String planNo) {
        return carService.selectCanChangePlanByPlanNo(planNo);
    }


    /**
     * 导出
     * @param queryVO 查询条件VO
     * @return ApiResult
     */
    @Override
    public ApiResult export(OtdPlanChangeApplyQueryVO queryVO) {
        return ResponseUtil.ok(applyPlanService.listByVo(queryVO));
    }
}
